#include "AxisRenderer.h"
#include "GraphicsDeviceManager.h"
#include "MatrixHelper.h"

AxisRenderer::AxisRenderer()
{
}

AxisRenderer::~AxisRenderer()
{
}

void AxisRenderer::Initialize()
{
	Vertex vertices[AXISRENDERER_VERTEX_COUNT];

	memset(vertices, 0, sizeof(Vertex) * AXISRENDERER_VERTEX_COUNT);

	vertices[0 ].Color = AXISRENDERER_LEFT_COLOR;
	vertices[1 ].Color = AXISRENDERER_LEFT_COLOR;
	vertices[1 ].Position = Vector3f(1.0f, 0.0f, 0.0f);
	vertices[2 ].Color = AXISRENDERER_LEFT_COLOR;
	vertices[2 ].Position = Vector3f(0.875f, 0.0f, 0.125f);
	vertices[3 ].Color = AXISRENDERER_LEFT_COLOR;
	vertices[3 ].Position = Vector3f(0.875f, 0.0f, -0.125f);

	vertices[4 ].Color = AXISRENDERER_UP_COLOR;
	vertices[5 ].Color = AXISRENDERER_UP_COLOR;
	vertices[5 ].Position = Vector3f(0.0f, 1.0f, 0.0f);
	vertices[6 ].Color = AXISRENDERER_UP_COLOR;
	vertices[6 ].Position = Vector3f(0.125f, 0.875f, 0.0f);
	vertices[7 ].Color = AXISRENDERER_UP_COLOR;
	vertices[7 ].Position = Vector3f(-0.125f, 0.875f, 0.0f);

	vertices[8 ].Color = AXISRENDERER_FORWARD_COLOR;
	vertices[9 ].Color = AXISRENDERER_FORWARD_COLOR;
	vertices[9 ].Position = Vector3f(0.0f, 0.0f, 1.0f);
	vertices[10].Color = AXISRENDERER_FORWARD_COLOR;
	vertices[10].Position = Vector3f(0.0f, 0.125f, 0.875f);
	vertices[11].Color = AXISRENDERER_FORWARD_COLOR;
	vertices[11].Position = Vector3f(0.0f, -0.125f, 0.875f);

	m_pVertexBuffer = new VertexBuffer();
	m_pVertexBuffer->SetData(vertices, sizeof(Vertex) * AXISRENDERER_VERTEX_COUNT);

	unsigned int indices[] = { 0, 1, 1, 2, 1, 3, 4, 5, 5, 6, 5, 7, 8, 9, 9, 10, 9, 11 };

	m_pIndexBuffer = new IndexBuffer();
	m_pIndexBuffer->SetData(indices, sizeof(unsigned int) * AXISRENDERER_INDEX_COUNT);

	m_bInitialized = true;
}

void AxisRenderer::Draw(const Vector3f& position, const Quaternion& rotation)
{
	if(!m_bInitialized)
	{
		Initialize();
	}

	// TODO: Move this GL call somewhere else
	glDisable(GL_TEXTURE_2D);
	glPushMatrix();
	glTranslatef(position.X, position.Y, position.Z);

	MatrixHelper::MultiplyRotation(rotation);

	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, m_pIndexBuffer->GetID());
	glBindBufferARB(GL_ARRAY_BUFFER_ARB, m_pVertexBuffer->GetID());
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);
	glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));
	glColorPointer(4, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(sizeof(Vector3f)));
	glDrawElements(GL_LINES, m_pIndexBuffer->GetElementCount(), GL_UNSIGNED_INT, 0);
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
	glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
	glPopMatrix();

	// TODO: Move this GL call somewhere else
	glEnable(GL_TEXTURE_2D);
}

bool AxisRenderer::m_bInitialized = false;
IndexBuffer* AxisRenderer::m_pIndexBuffer = NULL;
VertexBuffer* AxisRenderer::m_pVertexBuffer = NULL;